<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="单位名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入单位名称" clearable class="item"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="单位代码" prop="code">
          <el-input v-model="queryParams.code" placeholder="请输入单位代码" clearable class="item"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="区域" prop="areaId">
          <el-select v-model="queryParams.areaId" placeholder="请选择区域" class="item" clearable>
            <el-option v-for="item in areaOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" v-hasPerm="'sys_company_view'" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button type="success" icon="plus" v-hasPerm="'sys_company_add'" @click="handleOpenDialog('0')">新增</el-button>
        <el-button type="primary" icon="Expand" @click="expand">展开/折叠</el-button>
      </div>

      <el-table v-if="refresh" v-loading="loading" ref="tableTreeRef" :data="unitTableData" highlight-current-row row-key="id"
        :default-expand-all="expandAll" :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }">
        <el-table-column label="单位名称" align="left" min-width="150" prop="name" />
        <el-table-column label="所属区域" align="left" min-width="150" prop="areaId">
          <template #default="scope">
            {{ areaMap[scope.row.areaId] }}
          </template>
        </el-table-column>
        <el-table-column label="单位编码" align="left" min-width="150" prop="code" />
        <el-table-column label="电能类型" align="left" min-width="150" prop="energyType" />
        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button type="primary" link size="small" icon="plus" v-hasPerm="'sys_company_add'" @click.stop="handleOpenDialog(scope.row.id)">
              新增
            </el-button>

            <el-button type="primary" link size="small" icon="edit" v-hasPerm="'sys_company_edit'"
              @click.stop="handleOpenDialog(undefined, scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link size="small" icon="delete" v-hasPerm="'sys_company_del'" @click.stop="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-drawer v-model="dialog.visible" :title="dialog.title" :size="drawerSize" @close="handleCloseDialog">
      <el-form ref="unitFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="父级单位" prop="parentId">
          <el-tree-select v-model="formData.parentId" placeholder="选择上级单位" :data="unitOptions" filterable check-strictly
            :render-after-expand="false" />
        </el-form-item>

        <el-form-item label="单位名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item label="单位编码" prop="name">
          <el-input v-model="formData.code" placeholder="请输入单位编码" />
        </el-form-item>
        <el-form-item label="所属区域" prop="areaId">
          <el-select v-model="formData.areaId" placeholder="请选择所属区域" filterable clearable>
            <el-option v-for="item in areaList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="电能类型" prop="energyType">
          <el-select v-model="formData.energyType" placeholder="请选择电能类型">
            <el-option v-for="item in energyTypeList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from '@/store/modules/app.store';
import { DeviceEnum } from '@/enums/settings/device.enum';
import DeptAPI from '@/api/system/dept.api';
import UnitAPI, { UnitVO } from '@/api/system/unit.api';

defineOptions({
  name: 'SysUnit',
  inheritAttrs: false,
});

const appStore = useAppStore();

const queryFormRef = ref();
const unitFormRef = ref();

const refresh = ref(true);
const loading = ref(false);
const expandAll = ref(false);
const dialog = reactive({
  title: '新增单位',
  visible: false,
});

const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? '600px' : '90%'));
// 查询参数 parentId: '0'
const queryParams = reactive<any>({ name: '', code: '', areaId: '' });
const areaOptions = ref<any>([]);
// 单位表格数据
const unitTableData = ref<UnitVO[]>([]);
const tableTreeRef = ref<any>();
const areaMap: any = {};
// 顶级单位下拉选项
const unitOptions = ref<OptionType[]>([]);
// 初始单位表单数据
const initialUnitFormData = ref<any>({
  name: '',
  code: '',
  parentId: '',
  areaId: '',
  energyType: '',
});
// 单位表单数据
const formData = ref({ ...initialUnitFormData.value });
// 表单验证规则
const rules = reactive({
  parentId: [{ required: true, message: '请选择父级单位', trigger: 'blur' }],
  name: [{ required: true, message: '请输入单位名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入单位编码', trigger: 'blur' }],
  areaId: [{ required: true, message: '请选择所属区域', trigger: 'blur' }],
});

// 查询单位
function handleQuery() {
  loading.value = true;
  const params: any = {
    ...toRaw(queryParams),
  };
  for (let key in params) {
    if (params[key] === undefined || params[key] === null || params[key] === '') {
      delete params[key];
    }
  }
  UnitAPI.getTree(params)
    .then((data) => {
      unitTableData.value = data;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

const buildTree = (data: any) => {
  return data.map((item: any) => {
    const children = item.children || [];
    return {
      value: item.id,
      label: item.name,
      children: children.length > 0 ? buildTree(children) : [],
    };
  });
};

/**
 * 打开表单弹窗
 *
 * @param parentId 父单位ID
 * @param unitId 单位ID
 */
function handleOpenDialog(parentId?: string, row?: any) {
  UnitAPI.getTree()
    .then((data: any) => {
      unitOptions.value = [
        { value: '0', label: '顶级单位', children: data ? buildTree(data) : [] },
      ];
    })
    .then(() => {
      dialog.visible = true;
      if (row) {
        dialog.title = '编辑单位';
        formData.value = { ...row, id: row.id };
      } else {
        dialog.title = '新增单位';
        formData.value.parentId = parentId?.toString();
      }
    });
}

const expand = () => {
  expandAll.value = !expandAll.value;
  refresh.value = false;
  loading.value = true;
  console.log('tableTreeRef.value-', tableTreeRef.value);
  nextTick(() => {
    refresh.value = true;
    loading.value = false;
  });
};
/**
 * 提交表单
 */
function handleSubmit() {
  unitFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      const unitId = formData.value.id;
      const unitParams = { ...formData.value };
      console.log('unitParams-', unitParams);
      if (unitId) {
        //修改时父级单位不能为当前单位
        if (formData.value.parentId == unitId) {
          ElMessage.error('父级单位不能为当前单位');
          return;
        }
        UnitAPI.update(formData.value).then(() => {
          ElMessage.success('修改成功');
          handleCloseDialog();
          handleQuery();
        });
      } else {
        if (!unitParams?.params?.length) {
          delete unitParams.params;
        }
        UnitAPI.create(unitParams).then(() => {
          ElMessage.success('新增成功');
          handleCloseDialog();
          handleQuery();
        });
      }
    }
  });
}

// 删除单位
function handleDelete(unitId: any) {
  if (!unitId) {
    ElMessage.warning('请勾选删除项');
    return false;
  }

  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(
    () => {
      loading.value = true;
      UnitAPI.deleteByIds(unitId)
        .then(() => {
          ElMessage.success('删除成功');
          handleQuery();
        })
        .finally(() => {
          loading.value = false;
        });
    },
    () => {
      ElMessage.info('已取消删除');
    }
  );
}

function resetForm() {
  unitFormRef.value.resetFields();
  unitFormRef.value.clearValidate();
  formData.value = {
    id: undefined,
    parentId: '0',
    name: '',
    code: '',
    areaId: '',
    energyType: '',
    params: [],
  };
}
const areaList = ref<any>([]);
const energyTypeList = reactive<any[]>([
  { label: '储能', value: '储能' },
  { label: '风电', value: '风电' },
  { label: '光伏', value: '光伏' },
  { label: '燃煤', value: '燃煤' },
  { label: '燃气', value: '燃气' },
  { label: '热电联产', value: '热电联产' },
  { label: '生物质', value: '生物质' },
  { label: '水电', value: '水电' },
]);
const initAreaList = async () => {
  const data: any[] = await DeptAPI.getListAll();
  areaList.value = [...data];
  areaOptions.value = data.map((item: any) => {
    areaMap[item.id] = item.name;
    return {
      label: item.name,
      value: item.id
    }
  });
}
// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  resetForm();
}

onMounted(async () => {
  await initAreaList();
  handleQuery();
});
</script>

<style lang="scss" scoped>
.item {
  width: 220px;
}
</style>
